Sort Colors

Medium

Extra practice. This problem has no walkthrough slides. Try solving it with the pattern template on your own, and lean on the hints if you get stuck.

Question

Given a list containing only the values 0, 1, and 2, sort the list so that all the 0s come first, then all the 1s, then all the 2s.

Return the sorted list.

Input: nums = [2, 0, 2, 1, 1, 0]

Output: [0, 0, 1, 1, 2, 2]

Input: nums = [2, 0, 1]

Output: [0, 1, 2]

Input: nums = [0, 0, 1]

Output: [0, 0, 1]

The list is already sorted, so it stays the same.

Input: nums = [1]

Output: [1]

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Given nums = [1, 2, 0, 2, 1], what does the low/mid/high pointer approach return?
[0, 0, 1, 1, 2]
[0, 1, 1, 2, 2]
[1, 1, 0, 2, 2]
[0, 1, 2, 1, 2]

Take a moment to understand the problem and think of your approach before you start coding.